package com.jp.knowledge.view;

import android.content.Context;
import android.content.Intent;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.github.ybq.android.spinkit.SpinKitView;
import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jiayen.util.ToasUtil;
import com.jp.knowledge.R;
import com.jp.knowledge.activity.FoundAllActivity;
import com.jp.knowledge.activity.JpApplicationWebActivity;
import com.jp.knowledge.activity.SearchActivity;
import com.jp.knowledge.adapter.HomePageIconsAdapter;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.FoundAppData;
import com.jp.knowledge.model.FoundBanner;
import com.jp.knowledge.model.FundAppHome;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.my.base.RecycleVAdapter;
import com.jp.knowledge.util.ResultSubscriber;
import com.youth.banner.Banner;
import com.youth.banner.BannerConfig;
import com.youth.banner.listener.OnBannerListener;
import com.youth.banner.loader.ImageLoader;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Observable.OnSubscribe;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by 528787067@qq.com on 2017/3/14.
 */

public class HomePageView extends FrameLayout implements View.OnClickListener, ResultSubscriber.OnResultListener {

    private final static int GET_APPDATA_CODE = 0x01;
    private final static int GET_BANNER_CODE = 0x02;

    private Context context;
    private FileCacheManager cacheManager;
    private String appPath;
    private int screenHeight;
    private OnSubscribe<List<FundAppHome>> readAppCacheOnSubscribe;
    private Subscriber<List<FundAppHome>> readAppCacheSubscribe;
    private String bannerPath;
    private OnSubscribe<FoundBanner> readBannerCacheOnSubscribe;
    private Subscriber<FoundBanner> readBannerCacheSubscribe;

    private ImageView backgroundImage;
    private SpinKitView loading;
    private LinearLayout mainLayout;
    private ImageView mainIconImage;
    private LinearLayout searchView;
    private ImageView searchVoice;
    private ImageView searchQR;
    private RecyclerView iconBtnsVeiw;
    private HomePagePopularSearches popularSearchView;
    private Banner bannerView;
    private TextView watchMoreBtn;
    private ImageView switchSkinBtn;

    private HomePageIconsAdapter homePageIconsAdapter;
    private List<FundAppHome> foundAppDatas;
    private FoundBanner foundBanner;

    private Runnable changePaddingRunnable;
    private Runnable refreshAnimationRunnable;

    public HomePageView(Context context) {
        super(context);
        init();
    }

    public HomePageView(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HomePageView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    private void init(){
        context = getContext();
        screenHeight = getResources().getDisplayMetrics().heightPixels;
        View contentView = View.inflate(context, R.layout.home_page_view, this);
        backgroundImage = (ImageView) contentView.findViewById(R.id.bg_img);
        loading = (SpinKitView) contentView.findViewById(R.id.loading);
        mainLayout = (LinearLayout) contentView.findViewById(R.id.home_page_head);
        mainIconImage = (ImageView) contentView.findViewById(R.id.main_icon);
        searchView = (LinearLayout) contentView.findViewById(R.id.search_lly);
        searchVoice = (ImageView) contentView.findViewById(R.id.search_voice);
        searchQR = (ImageView) contentView.findViewById(R.id.search_qr);
        iconBtnsVeiw = (RecyclerView) contentView.findViewById(R.id.icon_btns_rv);
        popularSearchView = (HomePagePopularSearches) contentView.findViewById(R.id.popular_search_view);
        bannerView = (Banner) contentView.findViewById(R.id.banner_view);
        watchMoreBtn = (TextView) contentView.findViewById(R.id.watch_more_btn);
        switchSkinBtn = (ImageView) contentView.findViewById(R.id.switch_skin);

        bannerView.setBannerStyle(BannerConfig.CIRCLE_INDICATOR);
        bannerView.setIndicatorGravity(BannerConfig.CENTER);
        bannerView.setImageLoader(new ImageLoader(){
            @Override
            public void displayImage(Context context, Object path, ImageView imageView) {
                String imagePath = ((com.jp.knowledge.model.Banner)path).getSrc();
                if("R.drawable.headlines_default_banner".equals(imagePath))
                    imageView.setImageResource(R.drawable.headlines_default_banner);
                else
                    Glide.with(context).load(imagePath).error(R.mipmap.morentutouxiang).into(imageView);
            }
        });
        bannerView.setOnBannerListener(new OnBannerListener() {
            @Override
            public void OnBannerClick(int position) {
                if(foundBanner == null || foundBanner.getBanner() == null || foundBanner.getBanner().size() == 0)
                    return;
                List<com.jp.knowledge.model.Banner> banner = foundBanner.getBanner();

            }
        });

        iconBtnsVeiw.setLayoutManager(new GridLayoutManager(context, 5));
        iconBtnsVeiw.setHasFixedSize(true);
        homePageIconsAdapter = new HomePageIconsAdapter(context, new ArrayList<FoundAppData>());
        iconBtnsVeiw.setAdapter(homePageIconsAdapter);
        foundAppDatas = new ArrayList<>();
        homePageIconsAdapter.addItemClickListener(new RecycleVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                FoundAppData appData = homePageIconsAdapter.getData(position);
                String code = appData.getCode();
                if(appData.getIndexSort() == 10)
                    context.startActivity(new Intent(context, FoundAllActivity.class)
                            .putExtra("foundAppDatas", (Serializable) foundAppDatas));
                else if(!TextUtils.isEmpty(code))
                    JpApplicationWebActivity.gotoWebActivity(context, code);
                else
                    ToasUtil.toast(context, "抱歉，路径为空");
            }
        });

        changePaddingRunnable = new Runnable() {
            @Override
            public void run() {
                int paddingTop = mainLayout.getPaddingTop();
                paddingTop -= 50;
                if(paddingTop < 0)
                    paddingTop = 0;
                mainLayout.setPadding(0, paddingTop, 0, 0);
                if(paddingTop > 0)
                    mainLayout.postDelayed(changePaddingRunnable, 1);
            }
        };
        refreshAnimationRunnable = new Runnable() {
            @Override
            public void run() {
                loading.setVisibility(View.GONE);
            }
        };

        searchView.setOnClickListener(this);
        searchVoice.setOnClickListener(this);
        searchQR.setOnClickListener(this);
        watchMoreBtn.setOnClickListener(this);
        switchSkinBtn.setOnClickListener(this);

        initCache();
        readAppData();
        readBannerCache();
    }

    private void initCache(){
        cacheManager = new FileCacheManager();
        appPath = context.getCacheDir()+"/appdata_" /*+ HttpHelper.uuid */+ ".dat";
        bannerPath = context.getCacheDir()+"/banner_" /*+ HttpHelper.uuid*/ + ".dat";
        readAppCacheOnSubscribe = new OnSubscribe<List<FundAppHome>>() {
            @Override
            public void call(Subscriber<? super List<FundAppHome>> subscriber) {
                List<FundAppHome> appData = (List<FundAppHome>) cacheManager.readObject(appPath);
                subscriber.onNext(appData);
            }
        };
        readAppCacheSubscribe = new Subscriber<List<FundAppHome>>() {
            @Override
            public void onCompleted() {
                getAppData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(List<FundAppHome> data) {
                setAppData(data);
                onCompleted();
            }
        };
        readBannerCacheOnSubscribe = new OnSubscribe<FoundBanner>() {
            @Override
            public void call(Subscriber<? super FoundBanner> subscriber) {
                FoundBanner appData = (FoundBanner) cacheManager.readObject(bannerPath);
                subscriber.onNext(appData);
            }
        };
        readBannerCacheSubscribe = new Subscriber<FoundBanner>() {
            @Override
            public void onCompleted() {
                getBannerData();
            }
            @Override
            public void onError(Throwable e) {
                onCompleted();
            }
            @Override
            public void onNext(FoundBanner data) {
                foundBanner = data;
                setBannerData(foundBanner);
                onCompleted();
            }
        };
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.search_lly:       // 跳转到全局搜索
                context.startActivity(new Intent(context, SearchActivity.class));
                break;
            case R.id.search_voice:     // 语言输入
                if(this.homePageViewCallback != null)
                    homePageViewCallback.onVoiceInputClick();
                break;
            case R.id.search_qr:        // 二维码扫描
                if(this.homePageViewCallback != null)
                    homePageViewCallback.onQRCodeScanfClick();
                break;
            case R.id.watch_more_btn:   // 查看更多
                if(this.homePageViewCallback != null)
                    homePageViewCallback.onWatchMoreClick();
                break;
            case R.id.switch_skin:      // 切换皮肤
                break;
        }
    }

    /* 读取缓存的应用图标数据 */
    private void readAppData(){
        Observable.create(readAppCacheOnSubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(readAppCacheSubscribe);
    }

    /* 获取应用图标数据 */
    private void getAppData(){
        JsonObject param = new JsonObject();
//        param.addProperty("color", context.getString(R.string.theme_color_value));
        param.addProperty("type", 1);
        HttpHelper.getInstance(context).discoverApps(param, GET_APPDATA_CODE, this);
    }

    /* 将应用图标数据更新到界面中 */
    private void setAppData(List<FundAppHome> data){
        if(data == null || data.size() == 0){
            iconBtnsVeiw.setVisibility(View.GONE);
        } else{
            iconBtnsVeiw.setVisibility(View.VISIBLE);
            foundAppDatas.clear();
            foundAppDatas.addAll(data);

            List<FoundAppData> appDatas = new ArrayList<>();
            for(FundAppHome fundAppHome : foundAppDatas) {
                if (fundAppHome != null && fundAppHome.getGropuApps() != null
                        && fundAppHome.getGropuApps().size() > 0)
                    appDatas.addAll(fundAppHome.getGropuApps());
            }
            List<FoundAppData> subList = appDatas.subList(0, appDatas.size() > 10 ? 10 : appDatas.size());
            homePageIconsAdapter.updateAdapter(subList);
        }
    }

    /* 读取缓存的轮播图片数据 */
    private void readBannerCache(){
        Observable.create(readBannerCacheOnSubscribe)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(readBannerCacheSubscribe);
    }

    /* 获取轮播图标数据 */
    private void getBannerData(){
        HttpHelper.getInstance(context).discoverData(new JsonObject(), GET_BANNER_CODE, this);
    };

    /* 将轮播图片数据更新到界面中 */
    private void setBannerData(FoundBanner data){
        if(data == null || data.getBanner() == null || data.getBanner().size() == 0) {
            List<com.jp.knowledge.model.Banner> banners = new ArrayList<>();
            com.jp.knowledge.model.Banner banner = new com.jp.knowledge.model.Banner();
            banner.setSrc("R.drawable.headlines_default_banner");
            banners.add(banner);
            bannerView.update(banners);
        } else {
            bannerView.update(data.getBanner());
        }
    };

    /* 处理触摸移动事件，用于与 UCViewHeaderBehavior 交互 */
    public boolean handleTouchMove(int dy, boolean isAtTop){
        if(!isAtTop)
            return false;
        if(loading.getVisibility() == View.VISIBLE)
            return false;
        int paddingTop = mainLayout.getPaddingTop();
        if(dy >= 0 && paddingTop <= 0)
            return false;
        paddingTop = paddingTop - dy/4;
        if(paddingTop > screenHeight * 0.3)
            paddingTop = (int)(screenHeight * 0.3 + 0.5);
        mainLayout.setPadding(0, paddingTop, 0, 0);
        return true;
    }
    /* 处理触摸抬起事件，用于与 UCViewHeaderBehavior 交互 */
    public void handleTouchUp(boolean isAtTop){
        if(!isAtTop)
            return;
        if(mainLayout.getPaddingTop() > screenHeight * 0.1)
            refreshHomePage();
        mainLayout.post(changePaddingRunnable);
    }

    /* 刷新数据 */
    private void refreshHomePage(){
        loading.setVisibility(View.VISIBLE);
        loading.postDelayed(refreshAnimationRunnable, 5000);    // 5秒没刷新完成则隐藏加载动画
        getAppData();
        getBannerData();
        popularSearchView.refreshPopularSearch();
        if(homePageViewCallback != null)
            homePageViewCallback.refreshData();
    }

    public void dataRefreshFinish(){
        loading.setVisibility(View.GONE);
        loading.removeCallbacks(refreshAnimationRunnable);
    }

    @Override
    public void onStart(int requestType) {}
    @Override
    public void onCompleted(int requestType) {}
    @Override
    public void onError(int requestType) {
        onCompleted(requestType);
    }
    @Override
    public void onNext(IModel data, int requestType) {
        if(data.getErrcode() != 0){
            onError(requestType);
        } else if(requestType == GET_APPDATA_CODE){
            List<FundAppHome> list = data.getList(FundAppHome.class);
            setAppData(list);
            saveDataToCache(list, appPath);
        } else if(requestType == GET_BANNER_CODE){
            foundBanner = data.getEntity(FoundBanner.class);
            setBannerData(foundBanner);
            saveDataToCache(foundBanner, bannerPath);
        }
    }

    /* 缓存数据到本地 */
    private void saveDataToCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                cacheManager.wirteObject(data, path);
            }
        }).start();
    }

    private HomePageViewCallback homePageViewCallback;
    public void setHomePageViewCallback(HomePageViewCallback homePageViewCallback){
        this.homePageViewCallback = homePageViewCallback;
    }
    public interface HomePageViewCallback {
        void onVoiceInputClick();
        void onQRCodeScanfClick();
        void onWatchMoreClick();
        void refreshData();
    }
}
